﻿using IServices;
using Lazy.Captcha.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using NDLS.WebApi.Common.Encrypted;
using NDLS.WebApi.Common.JWT;
using NDLS.WebApi.Model;
using NDLS.WebApi.Model.ModelVM;
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace Services
{
    public class UserService : IUserService
    {
        private readonly EncryptedPwd _encryptedPwd = new EncryptedPwd();
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly string _secretKey; // 密钥
        private readonly ICaptcha _captcha;

        public UserService(IConfiguration configuration, IHttpContextAccessor httpContextAccessor, ICaptcha captcha)
        {
            _secretKey = configuration["pwdSecretKey"] ?? "1234567812345678"; // 从配置文件中获取密钥
            _httpContextAccessor = httpContextAccessor;
            _captcha = captcha;
        }

        public MsgRes Register(string username, string password)
        {
            using (var context = new NdlsContext()) // 创建数据库上下文实例
            {
                var user = context.SmPeople.FirstOrDefault(u => u.Username == username);
                if (user != null)
                {
                    return new MsgRes { Status = "Error", Msg = "用户名已存在" };
                }
                else
                {
                    // 生成随机的IV
                    byte[] iv = _encryptedPwd.GenerateRandomIV();

                    // 使用AES128、CBC模式和PKCS7填充来加密密码
                    string Password = _encryptedPwd.EncryptPassword(password, _secretKey, iv);

                    SmPerson person = new SmPerson();
                    // 设置用户的用户名和IV + 加密后的密码
                    person.Username = username;
                    person.Password = Password;
                    person.Role = "1";
                    try
                    {
                        // 将用户对象添加到数据库
                        context.SmPeople.Add(person);
                        context.SaveChanges(); // 保存更改到数据库
                        return new MsgRes { Status = "Success", Msg = "注册成功" };
                    }
                    catch
                    {
                        return new MsgRes { Status = "Error", Msg = "注册失败" };
                    }
                }
            }
        }

        public MsgRes Login(string username, string password, string code)
        {
            using (var context = new NdlsContext())
            {
                var user = context.SmPeople.FirstOrDefault(u => u.Username == username);

                if (user == null)
                {
                    // 用户不存在的情况
                    return new MsgRes { Status = "Error", Msg = "用户名或密码不正确" };
                }

                // 解码Base64的存储密码
                byte[] storedPasswordBytes = Convert.FromBase64String(user.Password ?? "");

                // 提取IV和加密的密码部分
                byte[] iv = storedPasswordBytes.Take(16).ToArray();

                // 使用存储的IV和密钥对用户提供的密码进行加密
                string encryptedUserPassword = _encryptedPwd.EncryptPassword(password, _secretKey, iv);

                // 将加密后的用户提供的密码与存储的密码进行比较
                if (encryptedUserPassword == Convert.ToBase64String(storedPasswordBytes))
                {      
                    string id = "whx1004";
                    if (_captcha.Validate(id, code))
                    {
                        var token = jwtHelper.IssueJwt(user);
                        HttpContext httpContext = _httpContextAccessor.HttpContext;
                        httpContext.Response.Cookies.Append("Token", token, new CookieOptions
                        {
                            Expires = DateTime.Now.AddMinutes(20)
                        });
                        // 密码正确，返回成功消息
                        return new MsgRes { Status = "Success", Msg = "登录成功", Token = token };
                    }
                    else
                    {
                        return new MsgRes { Status = "Error", Msg = "验证码错误"};
                    }
                }
                else
                {
                    // 密码不正确，返回通用错误消息
                    return new MsgRes { Status = "Error", Msg = "用户名或密码不正确" };
                }
            }
        }

        public SmPerson GetUserInfo()
        {
            HttpContext httpContext = _httpContextAccessor.HttpContext;
            string tokenValue = httpContext.Request.Cookies["Token"];
            return jwtHelper.DeserializeJwt(tokenValue);
        }

        //删除基地
        public MsgRes DeleteBase(int no, string trainingBase)
        {
            using (var context = new NdlsContext())
            {
                var _base = context.BaseCourses.FirstOrDefault(b => b.No == no && b.TrainingBase==trainingBase);
                if (_base == null)
                {
                    return new MsgRes { Status = "Error", Msg = "没有该基地，无法删除" };
                }
                else
                {
                    try
                    {
                        context.BaseCourses.Remove(_base);
                        context.SaveChanges();
                        return new MsgRes { Status = "Success", Msg = "基地删除成功"};
                    }
                    catch 
                    {
                        return new MsgRes { Status = "Error", Msg = "基地删除失败" };
                    }

                }
            }
        }

        //修改基地信息
        public MsgRes ModifyBase(BaseCourse baseCourse)
        {
            using (var context = new NdlsContext())
            {
                var existingBase = context.BaseCourses.FirstOrDefault(b => b.Id== baseCourse.Id);
                if (existingBase != null)
                {
                    try
                    {
                        // 更新基地信息
                        existingBase.No=baseCourse.No;
                        existingBase.TrainingBase = baseCourse.TrainingBase;
                        existingBase.PersonId=baseCourse.PersonId;
                        existingBase.Address = baseCourse.Address;
                        existingBase.Describe = baseCourse.Describe;
                       
                        // 根据需要更新其他字段

                        context.SaveChanges(); // 保存更改到数据库

                        return new MsgRes { Status = "Success", Msg = "更新成功" };
                    }
                    catch (Exception ex)
                    {
                        return new MsgRes { Status = "Error", Msg = "更新失败: " + ex.Message };
                    }
                }
                else
                {
                    return new MsgRes { Status = "Error", Msg = "基地不存在" };
                }
            }
        }



        //获取基地信息
        public List<MsgRes> GetBaseInfo(string trainingBase)
        {
            using (var context = new NdlsContext())
            {
                var bases = context.BaseCourses.Where(b => b.TrainingBase == trainingBase).ToList();
                if (bases.Count == 0)
                {
                    return new List<MsgRes> { new MsgRes { Status = "Error", Msg = "没有该基地" } };
                }
                else
                {
                    List<MsgRes> result = bases.Select(baseItem => new MsgRes { Status = "Success", Msg = "有该基地", BaseInfo = baseItem }).ToList();
                    return result;
                }
            }
        }

        public object GetAllBase(int currentPage, int pageSize)
        {
            using (var context = new NdlsContext())
            {
                var bases = context.BaseCourses.ToList();
                int totalNums = bases.Count;

                if (bases.Count == 0)
                {
                    return new { TotalNums = totalNums, Data = new List<MsgRes> { new MsgRes { Status = "Error", Msg = "没有基地信息" } } };
                }
                else
                {
                    List<MsgRes> result = bases
                        .Skip((currentPage - 1) * pageSize)
                        .Take(pageSize)
                        .Select(baseItem => new MsgRes { Status = "Success", Msg = "有基地信息", BaseInfo = baseItem })
                        .ToList();

                    return new { TotalNums = totalNums, Data = result };
                }
            }
        }


        //添加基地信息
        public MsgRes AddBase(BaseCourse baseCourse)
        {
            using (var context = new NdlsContext()) // 创建数据库上下文实例
            {
                var _base = context.BaseCourses.FirstOrDefault(b => b.Id == baseCourse.Id);
                if (_base != null)
                {
                    return new MsgRes { Status = "Error", Msg = "基地已存在" };
                }
                else
                {
                    try
                    {
                        // 将用户对象添加到数据库
                        context.BaseCourses.Add(baseCourse);
                        context.SaveChanges(); // 保存更改到数据库
                        return new MsgRes { Status = "Success", Msg = "添加成功" };
                    }
                    catch
                    {
                        return new MsgRes { Status = "Error", Msg = "添加失败" };
                    }
                }
            }
        }

        //添加课程信息
        public MsgRes AddCourse(ClassInfo classInfo)
        {
            using (var context = new NdlsContext()) // 创建数据库上下文实例
            {
                    try
                    {
                        SmPerson People = GetUserInfo();

                        Course course = new Course();
                        course.Name = classInfo.Name;
                        course.Title = classInfo.Title;
                        course.Description = classInfo.Description;
                        course.Category = classInfo.Category;
                        course.Enable = classInfo.Enable;
                        course.CreatePerson = People.Username;
                        course.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        context.Courses.Add(course);
                        context.SaveChanges();

                        ClassBegin classBegin = new ClassBegin();
                        classBegin.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        classBegin.Creator = People.Username;
                        classBegin.TeacherId = classInfo.TeacherId;
                        classBegin.StartTime = classInfo.StartTime;
                        classBegin.EndTime = classInfo.EndTime;
                        classBegin.Periods = classInfo.Periods;
                        classBegin.CourseId = context.Courses.FirstOrDefault(b => b.Name == course.Name && b.Description == course.Description)?.Id;
                        context.ClassBegins.Add(classBegin);

                        context.SaveChanges(); // 保存更改到数据库
                        return new MsgRes { Status = "Success", Msg = "课程添加成功" };
                    }
                    catch (Exception ex)
                    {
                        return new MsgRes { Status = "Error", Msg = "课程添加失败", ErrorDetails = ex.Message };
                    }
                
            }
        }

        public List<MsgRes> GetBaseInfoByArea(string area)
        {
            using (var context = new NdlsContext())
            {
                var bases = context.BaseCourses.Where(b => b.Area == area).ToList();
                if (bases.Count == 0)
                {
                    return new List<MsgRes> { new MsgRes { Status = "Error", Msg = "没有该基地" } };
                }
                else
                {
                    List<MsgRes> result = bases.Select(baseItem => new MsgRes { Status = "Success", Msg = "有该基地", BaseInfo = baseItem }).ToList();
                    return result;
                }
            }
        }
    }
}



